﻿using CarparkIMS_Model.Mapping;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CarparkIMS_Model
{

    //To use: services.AddDbContextPool<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YourDatabase")));
    public partial class MyContext : DbContext 
    {
        public MyContext(DbContextOptions options) : base(options)
        { }

        public virtual new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
            return base.Set<TEntity>();
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //dynamically load all entity and query type configurations
            var typeConfigurations = Assembly.GetExecutingAssembly().GetTypes().Where(type =>
                (type.BaseType?.IsGenericType ?? false)
                    && (type.BaseType.GetGenericTypeDefinition() == typeof(CustomEntityTypeConfiguration<>)
                        || type.BaseType.GetGenericTypeDefinition() == typeof(CustomQueryTypeConfiguration<>)));

            foreach (var typeConfiguration in typeConfigurations)
            {
                var configuration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration);
                configuration.ApplyConfiguration(modelBuilder);
            }

            base.OnModelCreating(modelBuilder);
        }
    }
}
